
package com.phevos.web.db;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class DAOManager
{
    private static DAOManager instance = new DAOManager();
    
    private static final Logger logger = LoggerFactory.getLogger(DAOManager.class.getName());

    private HashMap<String, BaseDAO> daoMap = new HashMap<String, BaseDAO>();

    /**
     * ��ȡ����
     * 
     * @return DAOManager
     */
    public static DAOManager getInstance()
    {
        return instance;
    }

    /**
     * ˽�й�����
     */
    private DAOManager()
    {
    }

    /**
     * ��ʼ�������ļ�
     * 
     * @param filename String
     */
    public void initConfig(String filename)
    {
        try
        {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new File(filename));
            List list = document.getRootElement().elements("action");
            Iterator iter = list.iterator();
            while (iter.hasNext())
            {
                Element elem = (Element)iter.next();
                String name = elem.attributeValue("name").trim();
                String dao = elem.attributeValue("dao").trim();
                BaseDAO daoClass = (BaseDAO)Class.forName(dao).newInstance();
                Iterator params = elem.elementIterator("param");
                while (params.hasNext())
                {
                    Element p = (Element)params.next();
                    String paramName = p.element("name").getTextTrim();
                    String paramValue = p.element("value").getTextTrim();
                    daoClass.setParameter(paramName, paramValue);
                }
                daoMap.put(name, daoClass);
            }
        }
        catch (Exception ex)
        {
            logger.error("��ʼ��dao����ʧ��.",ex);
        }
    }

    /**
     * ��ݲ�ѯ�����ȡ��Ӧ��dao
     * 
     * @param action String
     * @return BaseDAO
     */
    public BaseDAO getDAO(String action)
    {
        BaseDAO dao = (BaseDAO)daoMap.get(action);
        return dao;
    }

    /**
     * ��ݲ�ѯ����õ���ѯ���
     * 
     * @param action String
     * @return List
     */
    public List query(String action, Object[] args)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("action is{},args is{}", action, args);
        }
        BaseDAO dao = getDAO(action);      
        if (dao == null)
        {
            return null;
        }
        return dao.query(args);
    }
}
